package com.wyz.saas.common.base

import android.app.Application
import android.os.*
import androidx.multidex.MultiDex
import com.atom.api.ApiContext
import com.atom.core.AtomApi
import com.atom.module.mvvm.AppManager
import com.atom.module.mvvm.base.AbstractApplication
import java.io.File

abstract class AbstractApiApplication : AbstractApplication() {

    companion object {
        fun getInstance(): AbstractApiApplication {
            return applicationInstance as AbstractApiApplication
        }
    }

    private var handler: Handler? = null

    fun handle(): Handler? {
        if (handler == null) {
            handler = initHandle()
        }
        return handler
    }

    fun apiContext(): ApiContext {
        return AtomApi.getInstance()
    }

    override fun onCreate() {
        super.onCreate()
        // Atom
        AtomApi.newInstance(this, true)
    }

    open fun initHandle(): Handler {
        return Handler(Looper.getMainLooper())
    }

    fun send(msg: Message) {
        handle()?.sendMessage(msg)
    }

    override fun initApplication(): Application {
        return this
    }

    open fun finishAll() {
        AppManager.instance.finishAllActivity()
    }

    fun getCacheDirFile(): File {
        return applicationInstance.cacheDir
    }

    /**
     * 得到头像目录的缓存地址
     */
    fun getPortraitTmpFile(): File {
        val dir = File(getCacheDirFile(), "portrait")
        dir.mkdirs()
        val files = dir.listFiles()
        if (files != null && files.isNotEmpty()) {
            for (file in files) {
                file.delete()
            }
        }
        val path = File(dir, SystemClock.uptimeMillis().toString() + ".jpg")
        return path.absoluteFile
    }

    /**
     * 获取声音文件的本地地址
     * @param isTmp 是否是缓存文件， True，每次返回的文件地址是一样的
     * @return 录音文件的地址
     */
    fun getAudioTmpFile(isTmp: Boolean): File {
        val dir = File(getCacheDirFile(), "audio")
        dir.mkdirs()
        val files = dir.listFiles()
        if (files != null && files.isNotEmpty()) {
            for (file in files) {
                file.delete()
            }
        }
        // aar
        val path = File(
            getCacheDirFile(),
            if (isTmp) "tmp.mp3" else SystemClock.uptimeMillis().toString() + ".mp3"
        )
        return path.absoluteFile
    }


    fun logout() {

    }

}